package com.micro.frog.acct.service.impl;

import com.micro.frog.acct.dao.UserRoleMapper;
import com.micro.frog.acct.entity.RoleMenu;
import com.micro.frog.acct.entity.UserRole;
import com.micro.frog.acct.service.UserRoleService;
import com.micro.frog.acct.vo.RoleMenuVO;
import com.micro.frog.acct.vo.RoleUserVO;
import com.micro.frog.core.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author :  ljh
 * @date : 2018/4/12
 **/
@Service
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    UserRoleMapper userRoleMapper;

    @Override
    public List<RoleUserVO> queryRoleUser(Integer roleId) {
        return userRoleMapper.selectUserByRoleId(roleId);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void addUserRole(Integer roleId, List<Integer> userIds){
        for (Integer userId : userIds) {
            if (null != userId){
                UserRole userRole = new UserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(userId);
                userRoleMapper.insertSelective(userRole);
            }
        }
    }
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void updateRoleUsers(Integer roleId, String userIds) {
        userRoleMapper.deletedByRoleId(roleId);
        if(!StringUtils.isEmpty(userIds)){
            for (String userId : userIds.split(",")) {
                if (null != userId){
                    UserRole userRole = new UserRole();
                    userRole.setRoleId(roleId);
                    userRole.setUserId(Integer.parseInt(userId));
                    userRoleMapper.insertSelective(userRole);
                }
            }
        }
    }

    @Override
    public List<UserRole> all(UserRole userRole) {
        return userRoleMapper.selectByCondition(userRole);
    }

    @Override
    public int add(UserRole userRole) {
        return userRoleMapper.insertSelective(userRole);
    }

    @Override
    public int delete(Integer id) {
        return userRoleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int update(UserRole userRole) {
        return userRoleMapper.updateByPrimaryKey(userRole);
    }
}
